<template>
  <div class="app-container">
    <div class="main" @click.stop="clickOther">
      <div class="guidance-main" >
        <div class="patient-baseInfo">
          <div class="baseInfo-item">姓名： {{patient.patientName}}</div>
          <div class="baseInfo-item">性别： {{patient.patientSex}}</div>
          <div class="baseInfo-item">年龄： {{patient.patientAge}}</div>
        </div>
        <el-divider ></el-divider>
        <div class="guidanceInfo" >
          <el-table
            table-layout="auto"
            class="table-class"
            :show-header="false"
            :data="form.visitPatientCheckList"
            element-loading-text="Loading"
            border
          > 
            <el-table-column min-width="150" align="center">
              <template slot-scope="scope">
                <span style="font-weight: 600;font-size: 18px;">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="600" align="center">
              <template slot-scope="scope">
                <div  @click.stop="firstFocus(scope.row)">
                  <el-input type="textarea" autosize resize="none" v-model="scope.row.value"></el-input>
                </div>
                <div v-show="scope.row.isFocus" style="display: flex;flex-direction: row;justify-content: flex-start;position: relative;top: 0px;width: 98%;background-color: white;padding: 10px;border: 1px solid gray;">
                  <span @click.stop>  <!-- 防止冒泡 -->
<!--                     
                      <el-popover
                        style="position: relative"
                        placement="bottom"
                        width="200"
                        trigger="hover"
                        content=""
                        v-for="(secondItem, secondIndex) in scope.row.children" :key="secondIndex"
                        >
                        <el-button :id="secondItem.id" style="margin-left: 10px;font-size: 18px;" type="text" slot="reference" @click.stop="selectSecond(scope.ro, secondItem)" @mouseover.native="onHover(scope.row, secondItem)">{{secondItem.name}}</el-button>
                        <div style="display: inline-block;margin-left: 10px;font-size: 16px" v-for="(thirdItem, thirdIndex) in secondItem.children" :key="thirdIndex" @click.stop="selectThird(scope.row, secondItem, thirdItem)">
                          <a >{{ thirdItem.name }}</a>
                        </div>
                      </el-popover> -->
                    <el-tabs ref="navTabs" tab-position="top" style="height: 200px;" @tab-click="(tab, event) => { clickTab(tab, event, scope.row)}" @mouseover.native="onHover" >
                      <el-tab-pane style="float: left;" :label="secondItem.name" v-for="(secondItem, secondIndex) in scope.row.children" :key="secondIndex" @click.stop="selectSecond(scope.row, secondItem)">
                        <div style="display: inline-block;margin-left: 10px;font-size: 16px" v-for="(thirdItem, thirdIndex) in secondItem.children" :key="thirdIndex" @click.stop="selectThird(scope.row, secondItem, thirdItem)">
                          <a >{{ thirdItem.name }}</a>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 处方 -->
          <div class="vist-drug-table">
            <div class="vist-drug-header">
              <h4>处方/检查</h4>
              <div class="vist-drug-header-btn-group">
                <el-button :type="issubpackageDrug?'primary':''" size="small" @click="showItem(1)">分装商品开具</el-button><el-button :type="isPackageDug?'primary':''" size="small" @click="showItem(2)">整装商品开具</el-button><el-button :type="isInspection?'primary':''" size="small" @click="showItem(3)">检查开具</el-button><el-button :type="isHerbalDrug?'primary':''" size="small" @click="showItem(4)">中草药开具</el-button>
              </div>
            </div>
            <div class="vist-drug-body">
              <div style="padding: 10px;">
                 <el-descriptions class="margin-top" :column="3" size="large">
                  <el-descriptions-item label="处方总价">{{ form.visit.planTotalAmount }}</el-descriptions-item>
                  <el-descriptions-item label="日均价">{{ form.visit.dailyAveragePrice }}</el-descriptions-item>
                  <el-descriptions-item label="月均价">{{ form.visit.monthlyAveragePrice }}</el-descriptions-item>
                </el-descriptions>
                 <el-descriptions class="margin-top" :column="2" size="large">
                  <el-descriptions-item label="开始发药日期">
                    <el-date-picker size="mini" v-model="form.visit.startusageTime" type="date" placeholder="选择日期" @input="inputStartTime" ></el-date-picker>
                  </el-descriptions-item>
                  <el-descriptions-item label="服药结束日期">
                    <el-date-picker size="mini" v-model="form.visit.endusageTime" type="date" placeholder="选择日期" :disabled="true"></el-date-picker>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
              <el-divider ></el-divider>
              <div v-if="issubpackageDrug" class="body-item">
                <div class="body-item-title" ><span>分装商品</span></div>
                <div class="body-item-contents">
                  <span style="dispaly: inline-block;margin: 5px;">分装商品总价: {{ form.subPackagePlanTotalAmount }}</span>
                  <el-autocomplete
                    value-key="pinyinCode"
                    class="inline-input"
                    v-model="subPackageDrugSearchValue"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入 拼音简码"
                    :trigger-on-focus="false"
                    @select="(item) => {handleSelect(item, 1)}"
                    style="width: 100%;"
                  >
                  <template slot-scope="{ item }">
                    <span >{{ item.code+' ' }}</span>
                    <span >{{ item.name+'/' }}</span>
                    <span >{{ item.commonName+' ' }}</span>
                    <span >{{ item.specs+' '  }}</span>
                  </template>
                  </el-autocomplete>
                  <el-table
                    style="width: 100%"
                    :data="form.visitSubPackageDrugList"
                    element-loading-text="Loading"
                    border
                    fit
                  > 
                    <el-table-column label="药品名" align="center" width="150">
                      <template slot-scope="scope">
                        {{ scope.row.name + ' ' + scope.row.commonName }}
                      </template>
                    </el-table-column>
                    <el-table-column label="规格" width="100" align="center" prop="specs"></el-table-column>
                    <el-table-column label="编号" width="100" align="center" prop="code"></el-table-column>
                    <el-table-column label="使用计量/次" align="center"  width="100">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.eachUsageAmount" placeholder="请选择" @input="inputEachUsageAmount(scope.row)">
                          <el-option
                            v-for="item in meteredEnum"
                            :key="item"
                            :label="item"
                            :value="item">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="用法" align="center" width="110">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.usageMode" placeholder="请选择" >
                          <el-option
                            v-for="item in usageModeEnum"
                            :key="item"
                            :label="item"
                            :value="item">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="处方天数" align="center" width="100">
                      <template slot-scope="scope">
                        <el-input type="Number" min=0 v-model="scope.row.planUsageDays" @blur="inputPlanUsageDays(scope.row)" placeholder="倍数4"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="开药天数" align="center" width="100">
                      <template slot-scope="scope">
                        <el-input type="Number" min=0 v-model="scope.row.realUsageDays" @blur="inputRealUsageDays(scope.row, scope.$index)" placeholder="倍数4"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="是否备用" align="center" width="100">
                      <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isStandby">备用</el-checkbox>
                      </template>
                    </el-table-column>
                    <el-table-column label="单价(片)" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.unitPrice }}
                      </template>
                    </el-table-column>
                    <el-table-column label="处方片数" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.planQuantity? scope.row.planQuantity : '' }}
                      </template>
                    </el-table-column>
                    <el-table-column label="开药片数" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.realQuantity ? scope.row.realQuantity : '' }}
                      </template>
                    </el-table-column>
                    <el-table-column label="处方售价" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.planSalePrice ? scope.row.planSalePrice : '' }}
                      </template>
                    </el-table-column>
                    <el-table-column label="开药售价" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.realSalePrice ? scope.row.realSalePrice : '' }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <div v-if="isPackageDug" class="body-item">
                <div class="body-item-title" ><span>整装商品</span></div>
                <div class="body-item-contents">
                  <span style="dispaly: inline-block;margin: 5px;">整装商品总价: {{ form.packageRealTotalAmount }}</span>
                  <el-autocomplete
                    value-key="pinyinCode"
                    class="inline-input"
                    v-model="packageDrugSearchValue"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入 拼音简码"
                    :trigger-on-focus="false"
                    @select="(item) => {handleSelect(item, 2)}"
                    style="width: 100%;"
                  >
                  <template slot-scope="{ item }">
                    <span >{{ item.code+' ' }}</span>
                    <span >{{ item.name+'/' }}</span>
                    <span >{{ item.commonName+' ' }}</span>
                    <span >{{ item.specs+' '  }}</span>
                  </template>
                  </el-autocomplete>
                  <el-table
                    style="width: 100%"
                    :data="form.visitPackageDrugList"
                    element-loading-text="Loading"
                    border
                    fit
                  > 
                    <el-table-column label="药品名" align="center" width="150">
                      <template slot-scope="scope">
                        {{ scope.row.name + ' ' + scope.row.commonName }}
                      </template>
                    </el-table-column>
                    <el-table-column label="规格" width="100" align="center" prop="specs"></el-table-column>
                    <el-table-column label="编号" width="100" align="center" prop="code"></el-table-column>
                    <el-table-column label="开具数量" align="center"  width="100">
                      <template slot-scope="scope">
                        <el-input type="Number" min=0 v-model="scope.row.realQuantity" @input="inputPackageRealQuantity(scope.row)" @blur="inputPackageRealQuantity(scope.row)" ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="单价(盒)" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.unitPrice }}
                      </template>
                    </el-table-column>
                    <el-table-column label="总价" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.realSalePrice ? scope.row.realSalePrice : '' }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <div v-if="isInspection" class="body-item">
                <div class="body-item-title" ><span>检查项</span></div>
                <div class="body-item-contents">
                  <span style="dispaly: inline-block;margin: 5px;">检查项总价: {{ form.inspectionRealTotalAmount }}</span>
                  <el-autocomplete
                    value-key="pinyinCode"
                    class="inline-input"
                    v-model="inspectionSearchValue"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入 拼音简码"
                    :trigger-on-focus="false"
                    @select="(item) => {handleSelect(item, 3)}"
                    style="width: 100%;"
                  >
                  <template slot-scope="{ item }">
                    <span >{{ item.code+' ' }}</span>
                    <span >{{ item.name+'/' }}</span>
                    <span >{{ item.commonName+' ' }}</span>
                    <span >{{ item.specs+' '  }}</span>
                  </template>
                  </el-autocomplete>
                  <el-table
                    style="width: 100%"
                    :data="form.visitInspectionList"
                    element-loading-text="Loading"
                    border
                    fit
                  > 
                    <el-table-column label="检查名" align="center" width="150">
                      <template slot-scope="scope">
                        {{ scope.row.name }}
                      </template>
                    </el-table-column>
                    <el-table-column label="编号" width="100" align="center" prop="code"></el-table-column>
                    <el-table-column label="开具数量" align="center"  width="100">
                      <template slot-scope="scope">
                        <el-input type="Number" min=0 v-model="scope.row.realQuantity" @input="inputPackageRealQuantity(scope.row)" @blur="inputPackageRealQuantity(scope.row)" ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="单价(盒)" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.unitPrice }}
                      </template>
                    </el-table-column>
                    <el-table-column label="总价" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.realSalePrice ? scope.row.realSalePrice : '' }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <div v-if="isHerbalDrug" class="body-item">
                <div class="body-item-title" ><span>中草药</span></div>
                <div class="body-item-contents">
                  <span style="dispaly: inline-block;margin: 5px;">中草药总价: {{ form.herbalRealTotalAmount }}</span>
                  <el-autocomplete
                    value-key="pinyinCode"
                    class="inline-input"
                    v-model="herbalDrugDrugSearchValue"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入 拼音简码"
                    :trigger-on-focus="false"
                    @select="(item) => {handleSelect(item, 4)}"
                    style="width: 100%;"
                  >
                  <template slot-scope="{ item }">
                    <span >{{ item.code+' ' }}</span>
                    <span >{{ item.name+'/' }}</span>
                    <span >{{ item.commonName+' ' }}</span>
                    <span >{{ item.specs+' '  }}</span>
                  </template>
                  </el-autocomplete>
                  <el-table
                    style="width: 100%"
                    :data="form.visitHerbalDrugList"
                    element-loading-text="Loading"
                    border
                    fit
                  > 
                    <el-table-column label="中成药名" align="center" width="150">
                      <template slot-scope="scope">
                        {{ scope.row.name }}
                      </template>
                    </el-table-column>
                    <el-table-column label="编号" width="100" align="center" prop="code"></el-table-column>
                    <el-table-column label="开具数量(克)" align="center"  width="100">
                      <template slot-scope="scope">
                        <el-input type="Number" min=0 v-model="scope.row.realQuantity" @input="inputHerbalUnitPrice(scope.row)" ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="进价" align="center" width="100">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.currentCostPrice" @input="inputHerbalUnitPrice(scope.row)"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="倍数" align="center" width="100">
                      <template slot-scope="scope">
                        <el-input type="Number" min=0 v-model="scope.row.multiple" @input="inputHerbalUnitPrice(scope.row)"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="总价" align="center" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.realSalePrice ? scope.row.realSalePrice : '' }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
            <div class="footer">
              <el-button type="warning" :loading="commitBtnLoading" @click="confirm(0)">提交</el-button>
              <div style="width:200px;display: inline-block;"> </div>
              <el-button type="primary" :loading="commitBtnLoading" @click="confirm(1)">完成</el-button>
              <div style="width:100px;display: inline-block;"> </div>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="patient-info">
        <h2>会员信息</h2>
        <div>
          <p>姓名: {{ this.patient.patientName }}</p>
          <p>性别: {{ this.patient.patientSex }}</p>
          <p>年龄: {{ this.patient.patientAge }}</p>
          <p>主治医生: {{ this.patient.doctorName }}</p>
          <p>就诊次数: 25次</p>
          <p>会员等级: 3级</p>
          <p>最近就诊时间: 2024-04-25 10:15:22</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { getInfo } from '@/api/visitTemplateJobOffice'
import { addOrUpdate} from '@/api/guidance'
import { getListByPinyinCode, queryByCodeAnDepositoryId } from '@/api/drug'
import { dateToString, stringToDate } from '@/utils/dateUtil'
import { add } from '@/api/visit'

export default {
  filters: {

  },
  data() {
    const validateWaitTime = (rule, value, callback) => {
      if (!value) callback(new Error('请输入候诊时间')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {
        visitPatientCheckList: [],
        visit: {},
        subPackagePlanTotalAmount: 0,
        visitSubPackageDrugList: [],
        packageRealTotalAmount: 0,
        visitPackageDrugList: [],
        inspectionRealTotalAmount: 0,
        visitInspectionList: [],
        herbalRealTotalAmount: 0,
        visitHerbalDrugList: [],
      },
      dialogTitle: '添加来源',
      depts:[],
      formRules: {
        waitTime: [{ required: true, trigger: 'blur', validator: validateWaitTime }]
      },
      typeEnum: [{id: 1, name: '店面就诊'},{id: 2, name: '邮寄'},{id: 3, name: '代取'},{id: 4, name: '代放'}],
      waitTimeEnum: ['5', '10', '15', '20', '30', '60', '120'],
      jobOfficeEnum: [],
      userEnum: [],
      workAddressEnum: [],
      registerPrice: 0,
      patient: {},
      loginDept: {},
      issubpackageDrug: false,
      isPackageDug: false,
      isInspection: false,
      isHerbalDrug: false,
      subPackageDrugSearchValue: '',
      packageDrugSearchValue: '',
      inspectionSearchValue: '',
      herbalDrugDrugSearchValue:'',
      meteredEnum: [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3],
      usageModeEnum: ['1次/早', '1次/中', '1次/晚'],
      commitBtnLoading: false,
      guidanceCode: undefined,
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.navTabs.$refs.nav.$nextTick(() => {
        // 此时tab的nav才渲染dom 否则拿不到el-tabs__item
        let target = document.getElementsByClassName("el-tabs__item");
        let that = this;
        for (let i = 0; i < target.length; i++) {
          target[i].addEventListener("mouseover", () => {
            that.$refs.navTabs.handleTabClick(1, String(i));
          });
        }
      });
    });
  },
  methods: {
    fetchData() {
      this.patient = this.$route.params
      this.patient.id = this.patient.patientId
      console.log(this.patient)
      getInfo({jobOfficeId: this.patient.jobOfficeId}).then(res=> {
        console.log(res)
        this.$set(this.form, 'visitPatientCheckList', res.data)
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该来源?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    add(row) {
      this.reset()
      this.dialogTitle = '添加来源'
      this.formVisible = true
    },
    confirm() {
      console.log(this.form)
      var userInfo = JSON.parse(JSON.stringify(this.$store.getters.userInfo))
      this.form.visit.doctorId = userInfo.id
      this.form.visit.patientId = this.patient.patientId
      this.form.visit.subPackagePlanTotalAmount = this.form.subPackagePlanTotalAmount
      this.form.visit.subPackageRealTotalAmount = this.form.subPackageRealTotalAmount
      this.form.visit.inspectionRealTotalAmount = this.form.inspectionRealTotalAmount
      this.form.visit.herbalRealTotalAmount = this.form.herbalRealTotalAmount
      this.form.visit.visitPatientCheckList = this.form.visitPatientCheckList


      // this.$refs.form.validate(valid => {
        // if (valid) {
          add(this.form).then(res=>{
            console.log(res)
            this.$message({
              message: '添加/修改成功',
              type: 'success'
            })
          }).catch(err=>{
            console.log(err)
          })
        // }
      // })
    },
    cancel() {
      this.$router.push('/guidance/patient');
    },
    reset(){
      this.form = {}
    },
    firstFocus(firstItem) {
      this.form.visitPatientCheckList.forEach(item=> {
        item.isFocus = false
      })
      firstItem.isFocus = true
    },
    clickTab(tab, event, firstItem) {
      console.log(firstItem)
      this.$set(firstItem, 'value', firstItem.value + '  ' + tab._props.label)
    },
    onHover(firstItem, secondItem) {
      // firstItem.children.forEach(item=> {
      //   var tmp = document.getElementById(item.id);
      //   tmp.setAttribute("style", "margin-left: 10px;font-size: 18px;boder-bottom:  2px solid white;")
      // })
      // var cur = document.getElementById(secondItem.id);
      // cur.setAttribute("style", "margin-left: 10px;font-size: 18px;boder-bottom: 2px solid blue;")
      // console.log(secondItem)
    },
    selectSecond(firstItem, secondItem) {
      this.$set(firstItem, 'value', firstItem.value + '  ' + secondItem.name)
    },
    selectThird(firstItem, secondItem, thirdItem) {
      this.$set(firstItem, 'value', firstItem.value + '  ' + secondItem.name + thirdItem.name)
    },
    clickOther() {
      this.form.visitPatientCheckList.forEach(item=> {
        item.isFocus = false
      })
    },
    showItem(opt) {
      if(opt === 1) {
        this.issubpackageDrug = !this.issubpackageDrug
        if(this.issubpackageDrug === false) {
          // remove
        }
      } else if (opt === 2) {
        this.isPackageDug = !this.isPackageDug
        if(this.isPackageDug === false) {
          // remove
        }
      } else if (opt === 3) {
        this.isInspection = !this.isInspection
        if(this.isInspection === false) {
          // remove
        }
      } else if (opt === 4) {
        this.isHerbalDrug = !this.isHerbalDrug
        if(this.isHerbalDrug === false) {
          // remove
        }
      }
    },
    querySearch(queryString, cb) {
      getListByPinyinCode(queryString, this.form.applyDepository).then(drugListRes=>{
        // 调用 callback 返回建议列表的数据
        cb(drugListRes.data);
      })
    },
    handleSelect(item, index) {
      item.drugCode = item.code
      item.guidanceCode = this.guidanceCode
      if(index == 1) {
        this.subPackageDrugSearchValue = ''
        this.form.visitSubPackageDrugList.push(JSON.parse(JSON.stringify(item)))
      } else if(index == 2) {
        this.packageDrugSearchValue = ''
        this.form.visitPackageDrugList.push(JSON.parse(JSON.stringify(item)))
      } else if(index == 3) {
        this.inspectionSearchValue = ''
        let visitInspection = JSON.parse(JSON.stringify(item))
        visitInspection.realQuantity = 1
        visitInspection.realSalePrice = visitInspection.unitPrice
        this.form.visitInspectionList.push(visitInspection)
        this.calculateInspectionTotalAmount()
        // 所有总价
        this.calculatePlanTotalAmount()
      } else if(index == 4) {
        this.herbalDrugDrugSearchValue =''
        this.form.visitHerbalDrugList.push(JSON.parse(JSON.stringify(item)))
      }
    },
    inputPlanUsageDays(row) {
      // 分装药品总价
      this.$set(this.form, 'subPackagePlanTotalAmount', 0)
      var planUsageDays = undefined
      if(row&&row.planUsageDays) planUsageDays = (row.planUsageDays+'').replace(/[^\d]/g,'')
      for (const subPackageDrug of this.form.visitSubPackageDrugList) {
        if(planUsageDays) {
          if (planUsageDays < 4 || planUsageDays % 4 > 2) {
            this.$set(subPackageDrug, 'planUsageDays', Number(planUsageDays - (planUsageDays % 4)) + 4)
            this.$set(subPackageDrug, 'realUsageDays', Number(planUsageDays - (planUsageDays % 4)) + 4)
          } else {
            this.$set(subPackageDrug, 'planUsageDays', Number(planUsageDays - (planUsageDays % 4)))
            this.$set(subPackageDrug, 'realUsageDays', Number(planUsageDays - (planUsageDays % 4)))
          }
        }
        
        if(row.isSpare == 1) continue
        // 处方片数
        if(subPackageDrug.eachUsageAmount && subPackageDrug.planUsageDays) {
          this.$set(subPackageDrug, 'planQuantity', subPackageDrug.eachUsageAmount * subPackageDrug.planUsageDays)
          this.$set(subPackageDrug, 'planSalePrice', subPackageDrug.planQuantity * subPackageDrug.unitPrice)
        }
        if(subPackageDrug.planSalePrice) {
          this.$set(this.form, 'subPackagePlanTotalAmount', Number(this.form.subPackagePlanTotalAmount) + Number(subPackageDrug.planSalePrice))
        }
      }
      this.inputRealUsageDays(row)
      // 所有总价
      this.calculatePlanTotalAmount()
    },
    inputRealUsageDays(row, index) {
      var realUsageDays = (row.realUsageDays+'').replace(/[^\d]/g,'')
      if(realUsageDays) {
        if (realUsageDays < 4 || realUsageDays % 4 > 2) {
          this.$set(row, 'realUsageDays', Number(realUsageDays - (realUsageDays % 4)) + 4)
        } else {
          this.$set(row, 'realUsageDays', Number(realUsageDays - (realUsageDays % 4)))
        }
      }
      // 开药片数
      if(row.eachUsageAmount && row.realUsageDays) {
        this.$set(row, 'realQuantity', row.eachUsageAmount * row.realUsageDays)
        if(row.isSpare != 1) {
          this.$set(row, 'realSalePrice', row.realQuantity * row.unitPrice)
        }
        if(row.planSalePrice) {
          this.$set(this.form, 'subPackageRealTotalAmount', Number(this.form.subPackagePlanTotalAmount) + Number(row.realSalePrice))
        }
      }
      // 是否添加余药
      if(row.planUsageDays != row.realUsageDays 
      && (!row.isSpare || row.isSpare && row.isSpare != 1) 
      && (!this.form.visitSubPackageDrugList[index+1] || this.form.visitSubPackageDrugList[index+1] && this.form.visitSubPackageDrugList[index+1].isSpare != 1)
      ) {
        row.isReserve = 1
        var space = JSON.parse(JSON.stringify(row))
        space.isSpare = 1
        space.name = '(余药)' + space.name
        space.realSalePrice = ''
        this.$set(space, 'realUsageDays', row.planUsageDays - row.realUsageDays)
        this.$set(space, 'realQuantity', row.eachUsageAmount * row.realUsageDays)
        this.form.visitSubPackageDrugList.splice(index+1, 0, space)
      }
    },
    inputEachUsageAmount(row) {
      if(row.isSpare == 1) return
      if(row.eachUsageAmount) row.eachUsageAmount = (row.eachUsageAmount+'').replace(/[^\d]/g,'')
      if(row.eachUsageAmount && row.planUsageDays) {
        this.$set(row, 'planQuantity', row.eachUsageAmount * row.planUsageDays)
        this.$set(row, 'planSalePrice', row.unitPrice * row.planQuantity)
      }
      if(row.eachUsageAmount && row.realUsageDays) {
        this.$set(row, 'realQuantity', row.eachUsageAmount * row.realUsageDays)
        this.$set(row, 'realSalePrice', row.unitPrice * row.realQuantity)
      }
      // 分装药品总价
      this.calculateSubPackageDrugTotalAmount()
      // 所有总价
      this.calculatePlanTotalAmount()
    },
    inputPackageRealQuantity(row) {
      if(row&&row.unitPrice) row.unitPrice = (row.unitPrice+'').replace(/[^\d]/g,'')
      if(row&&row.realQuantity) row.realQuantity = row.realQuantity.replace(/[^\d]/g,'')
      if(row&&row.unitPrice && row.realQuantity) {
        this.$set(row, 'realSalePrice', row.unitPrice * row.realQuantity)
      }
      // 整装药品总价
      this.calculatePackageDrugTotalAmount()
      // 检查项总价
      this.calculateInspectionTotalAmount()
      // 所有总价
      this.calculatePlanTotalAmount()
    },
    inputHerbalUnitPrice(row) {
      if(row.realQuantity) row.realQuantity = row.realQuantity.replace(/[^\d]/g,'')
      if(row.multiple) row.multiple = row.multiple.replace(/[^\d]/g,'')
      if(row.currentCostPrice && row.realQuantity && row.multiple) {
        this.$set(row, 'realSalePrice', row.currentCostPrice * row.realQuantity * row.multiple)
      }
      console.log("herbal:", row)
      // 中草药总价
      this.calculateHerbalDrugTotalAmount()
      // 所有总价
      this.calculatePlanTotalAmount()
    },
    inputStartTime() {
      if(this.form.visitSubPackageDrugList && this.form.visitSubPackageDrugList.length == 0) return;
      var startusageTime = stringToDate(this.form.visit.startusageTime)
      var endusageTime = new Date(startusageTime.setDate(startusageTime.getDate() + Number(this.form.visitSubPackageDrugList[0].planUsageDays)));
      this.$set(this.form.visit, 'endusageTime', endusageTime)
    },
    calculatePlanTotalAmount() {
      var planTotalAmount = Number(this.form.subPackagePlanTotalAmount) + Number(this.form.packageRealTotalAmount) + Number(this.form.inspectionRealTotalAmount) + Number(this.form.herbalRealTotalAmount)
      this.$set(this.form.visit, 'planTotalAmount', planTotalAmount)
      this.$set(this.form.visit, 'dailyAveragePrice', this.form.visit.planTotalAmount)
      this.$set(this.form.visit, 'monthlyAveragePrice', this.form.visit.planTotalAmount)
      if(this.form.visitSubPackageDrugList.length != 0) {
        this.$set(this.form.visit, 'dailyAveragePrice', (this.form.visit.planTotalAmount/this.form.visitSubPackageDrugList[0].planUsageDays).toFixed(2))
        var monthly = this.form.visitSubPackageDrugList[0].planUsageDays/28
        this.$set(this.form.visit, 'monthlyAveragePrice', (this.form.visit.planTotalAmount/(monthly >=1 ? monthly : 1)).toFixed(2))
      }

    },
    calculatePackageDrugTotalAmount() {
      this.$set(this.form, 'packageRealTotalAmount', 0)
      for (const packageDrug of this.form.visitPackageDrugList) {
        if(packageDrug.realSalePrice) {
          this.form.packageRealTotalAmount = Number(this.form.packageRealTotalAmount) + Number(packageDrug.realSalePrice)
        }
      }
    },
    calculateInspectionTotalAmount() {
      this.$set(this.form, 'inspectionRealTotalAmount', 0)
      for (const inspection of this.form.visitInspectionList) {
        if(inspection.realSalePrice) {
          this.form.inspectionRealTotalAmount = Number(this.form.inspectionRealTotalAmount) + Number(inspection.realSalePrice)
        }
      }
    },
    calculateSubPackageDrugTotalAmount() {
      this.$set(this.form, 'subPackagePlanTotalAmount', 0)
      for (const subPackageDrug of this.form.visitSubPackageDrugList) {
        if(subPackageDrug.planSalePrice && subPackageDrug.isSpare != 1) {
          this.$set(this.form, 'subPackagePlanTotalAmount', Number(this.form.subPackagePlanTotalAmount) + Number(subPackageDrug.planSalePrice))
        }
      }
    },
    calculateHerbalDrugTotalAmount() {
      this.$set(this.form, 'herbalRealTotalAmount', 0)
      for (const herbalDrug of this.form.visitHerbalDrugList) {
        if(herbalDrug.realSalePrice) {
          this.$set(this.form, 'herbalRealTotalAmount', Number(this.form.herbalRealTotalAmount) + Number(herbalDrug.realSalePrice))
        }
      }
    }
  }
}
</script>

<style scoped>

.main{
  display: flex;
  flex-direction: row;
}
.patient-info {
  position: absolute;
  right: 0px;
  display: flex;
  flex-direction: column;
  background-color: white;
  margin-top: -20px;
  padding: 20px;
  height: 1000px;
  width: 20%;
  overflow: auto;
  border: 1px solid gray;
}
.guidance-main {
  display: flex;
  flex-direction: column;
  width: 75%;
}
.patient-baseInfo {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.footer {
    margin-top: 100px;
    margin-left: 400px;
}
.guidanceInfo {
  /* display: flex;
  flex-direction: column;
  justify-content:flex-start; */
  align-items: center;
}
.table-class {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  position: relative;
}
.vist-drug-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  position: relative;
  background-color: white;
  margin-top: 10px;
}
.vist-drug-header {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  border-bottom: 1px solid rgb(203, 203, 203);
}
.vist-drug-header-btn-group {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
.vist-drug-body {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.body-item {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  border-bottom: 1px solid rgb(203, 203, 203);
  width: 100%;
}
.inline-input {
  width: 100%;
}
.body-item-title {
  text-align: center;
  padding: 5px;
  border-right: 1px solid rgb(203, 203, 203);
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 5%;
}
.body-item-contents {
  width: 95%;
  margin-top: 30px;
}
.footer {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 50px;
}

</style>